#!/usr/bin/python
# -*- coding: utf-8 -*-  
"""
@Project : hello 
@file : job_state_manager.py
@Author : shenj
@time : 2025/5/28 15:17
@func :
"""
# job_state_manager.py
from typing import Dict, Tuple, Optional
from mysql_demo import MySQLHelper


class JobStateManager:
    def __init__(self):
        self.original_states: Dict[Tuple[str, int], Tuple[int, int, str]] = {}

    def backup_original_state(self, db: MySQLHelper, bu: str, job_id: int) -> None:
        """备份任务原始状态"""
        sql = f"SELECT STATUS, RESTART, CRON FROM asw_etl_{bu}_job.XX_SCHEDULE_JOB WHERE job_id = {job_id};"
        result = db.query(sql)
        if result:
            state = result[0]
            self.original_states[(bu, job_id)] = (state['STATUS'], state['RESTART'], state['CRON'])

    def restore_original_state(self, db: MySQLHelper, bu: str, job_id: int) -> bool:
        """恢复原始状态"""
        if (bu, job_id) not in self.original_states:
            return False

        original_status, original_restart, original_cron = self.original_states[(bu, job_id)]
        current_state = db.query(f"SELECT STATUS, RESTART, CRON FROM asw_etl_{bu}_job.XX_SCHEDULE_JOB WHERE job_id = {job_id};")[0]

        if (
            current_state['STATUS'] == original_status and
            current_state['RESTART'] == original_restart and
            current_state['CRON'] == original_cron
        ):
            return True

        sql = f"""
            UPDATE asw_etl_{bu}_job.XX_SCHEDULE_JOB
            SET STATUS={original_status}, RESTART={original_restart}, CRON='{original_cron}'
            WHERE job_id = {job_id};
        """
        db.execute(sql)
        return True
